<template>
  <div class="sign">
    <div>
      颜色:<input type="color" v-model="color">
      粗细:<input type="range" v-model="lineWidth">
      <el-button type="primary" size="mini" @click="isPenMode = !isPenMode">{{isPenMode ? '橡皮' : '画笔'}}模式</el-button>
      <el-button size="mini" @click="clean">清空面板</el-button>
    </div>
     <canvas ref="canvas" width="500" height="400" class="pannel"></canvas>
  </div>
</template>

<script>
export default {
  name:'',
  data () {
    return {
      isPenMode: true, // 是否为画笔模式
      color: '#ccc',
      lineWidth: '1',
      canDraw: false, // 是否能画
    };
  },
  computed:{
    canvas(){
      return this.$refs.canvas
    },
    context(){
      return this.canvas.getContext("2d")
    }
  },
  watch: {
    color(c){
      this.context.strokeStyle = c
    },
    lineWidth(w){
      if(w < 1) w = 1
      this.context.lineWidth = w
    }
  },
  mounted(){
    const {canvas, context} = this
    this.context.strokeStyle = this.color
    this.context.lineWidth = this.lineWidth
    const left = canvas.offsetLeft
    const top = canvas.offsetTop
    window.onmousemove = (e) => {
      if(this.canDraw){
        // 2. 开始描边
        if(this.isPenMode){ // 画笔模式
          context.lineTo(e.pageX - left, e.pageY - top)
          context.stroke()
        }else{ // 橡皮模式
          context.strokeStyle = '#fff'
          // context.rect
        }
      }
    },
    window.onmouseup = (e) =>{
      this.canDraw = false
      // 3. 结束
      context.closePath()
    },
    canvas.onmousedown = (e) => {
      this.canDraw = true
      // 1.将画笔移动到对应位置
      context.moveTo(e.pageX - left, e.pageY - top)

      // 3. 结束上一次的画笔
      context.beginPath();
    }
  },
  methods: {
    clean(){
      this.context.clearRect(0,0,500,400);
    }
  }
}

</script>
<style lang='less' scoped>
.pannel{
  border:1px solid #000000;
  background: #fff;
  margin-top: 20px;
}
</style>